package com.zdw.demo.proxy;

import com.zdw.demo.service.ProxyService;
import com.zdw.demo.service.impl.ProxyTwoServiceImpl;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * <p>
 * CGLIB动态代理--实现InvocationHandler接口
 * </p>
 *
 * @author 卓德文
 * @since 2022-3-24
 */
public class CglibProxyFactory implements MethodInterceptor {

    /**
     * 代理中持有的目标类
     */
    private Object target;

    /**
     * 构造方法
     *
     * @param target
     */
    public CglibProxyFactory(Object target) {
        this.target = target;
    }

    /**
     * 创建代理对象
     */
    public Object createProxy() {
        //1.创建Enhancer
        Enhancer enhancer = new Enhancer();
        //2.传递目标对象的class
        enhancer.setSuperclass(target.getClass());
        //3.设置回调操作
        enhancer.setCallback(this);
        //4.创建代理对象
        //注意:参数--实现MethodInterceptor接口的对象,即当前类对象this
        return enhancer.create();
    }

    /**
     * 代理方法
     *
     * @param proxy       代理类
     * @param method      目标方法
     * @param objects     执行目标类的方法的参数
     * @param methodProxy
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Object proxy, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("CGLIB动态代理--Before");
        Object invoke = methodProxy.invoke(target, objects);
        System.out.println("CGLIB动态代理--After");
        return invoke;
    }

    /**
     * 测试JDK动态代理
     *
     * @param args
     */
    public static void main(String[] args) {
        //1.拿到接口实现类对象
        //ProxyOneServiceImpl impl1 = new ProxyOneServiceImpl();
        ProxyTwoServiceImpl impl2 = new ProxyTwoServiceImpl();
        //2.拿到JDK动态代理对象的工厂类
        CglibProxyFactory proxyFactory = new CglibProxyFactory(impl2);
        //3.创建JDK动态代理对象
        ProxyService proxy = (ProxyService) proxyFactory.createProxy();
        //4.使用代理对象调用方法
        proxy.basketball();
    }

}
